package ltd.starriddle.smart4j.chapter2.controller;

import ltd.starriddle.smart4j.chapter2.model.Customer;
import ltd.starriddle.smart4j.chapter2.service.CustomerService;
import ltd.starriddle.smart4j.chapter2.util.CastUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 删除客户
 *
 * @author chen
 */
@WebServlet("/customer_delete")
public class CustomerDeleteServlet extends HttpServlet {

    private static final Logger LOGGER = LoggerFactory.getLogger(CustomerDeleteServlet.class);

    private CustomerService customerService;

    @Override
    public void init() throws ServletException {
        customerService = new CustomerService();
    }

    /**
     * 进入 删除客户 界面
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        long id = CastUtil.castLong(req.getParameter("id"));
        LOGGER.info("删除客户 id={}", id);

        Customer customer = customerService.getCustomer(id);
        req.setAttribute("customer", customer);
        LOGGER.info("删除客户 customer={}", customer);

        req.getRequestDispatcher("/WEB-INF/view/customer_delete.jsp").forward(req, resp);
    }

    /**
     * 处理 删除客户 请求
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        long id = CastUtil.castLong(req.getParameter("id"));
        LOGGER.info("req 删除客户 id={}", id);

        boolean result = false;
        String msg = "删除失败";
        Customer customer = customerService.getCustomer(id);
        if (customer == null) {
            msg = "客户不存在";
        } else {
            result = customerService.deleteCustomer(id);
            if (result) {
                result = true;
                msg = "删除成功";
            }
        }
        req.setAttribute("result", result);
        req.setAttribute("msg", msg);
        req.setAttribute("customer", customer);
        LOGGER.info("resp 删除客户 id={} result={} customer={}", id, result, customer);

        req.getRequestDispatcher("/WEB-INF/view/customer_delete.jsp").forward(req, resp);
    }
}
